package com.bh.ly.oa.activity;

import java.io.IOException;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bh.ly.oa.BaseActivity;
import com.bh.ly.oa.GlobalData;
import com.bh.ly.oa.R;
import com.bh.ly.oa.util.AsyncTaskFactory;
import com.bh.ly.oa.util.Config;
import com.bh.ly.oa.util.Util;
import com.dd.plist.NSArray;
import com.dd.plist.PropertyListParser;
import com.google.gson.Gson;

public class LoginActivity extends BaseActivity {

	private TextView title;
	private EditText uid, upwd;
	private CheckBox checkBox;
	private ImageButton btnLogin;
	private View startLogin;
	private boolean isRemeber;

	private LoginAsyncTask task;

	SharedPreferences sharedPreferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		// 解决android 4.0版本 network 问题
		// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		// .detectDiskReads()
		// .detectDiskWrites()
		// .detectNetwork() // or .detectAll() for all detectable problems
		// .penaltyLog()
		// .build());
		// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
		// .detectLeakedSqlLiteObjects()
		// .detectLeakedClosableObjects()
		// .penaltyLog()
		// .penaltyDeath()
		// .build());
		sharedPreferences = getSharedPreferences("Account", 0);

		startLogin = findViewById(R.id.start_login_layout);
		checkBox = (CheckBox) findViewById(R.id.check_box);
		title = (TextView) findViewById(R.id.title_textview);
		btnLogin = (ImageButton) findViewById(R.id.back_button);
		title.setText("登录");
		uid = (EditText) findViewById(R.id.login_uid);
		uid.setText(sharedPreferences.getString("uid", ""));
		upwd = (EditText) findViewById(R.id.login_pwd);
		upwd.setText(sharedPreferences.getString("pass", ""));
		if (sharedPreferences.getString("address", "") != null && sharedPreferences.getString("address", "").length() > 0) {
			Config.domain = "http://" + sharedPreferences.getString("address", "") + ":" + sharedPreferences.getString("portel", "") + "/";
			if (sharedPreferences.getString("appname", "") != null && sharedPreferences.getString("appname", "").length() > 0)
				Config.domain = Config.domain + sharedPreferences.getString("appname", "") + "/";
		}
		if (isVerifiedLogin()) {
			checkBox.setChecked(true);
		}

		btnLogin.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				if (verificationLogin()) {
					LoginRequse();
				}

			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, 1, 0, "连接服务器设置");
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		Log.i("info", "ready to take photos!");
		Intent intent = new Intent(LoginActivity.this, SettingActivity.class);
		startActivity(intent);
		return true;
	}

	private boolean isVerifiedLogin() {
		if (uid.getText() == null || uid.getText().length() <= 0) {
			return false;
		}

		if (upwd.getText() == null || upwd.getText().length() <= 0) {
			return false;
		}

		return true;
	}

	private boolean verificationLogin() {
		if (uid.getText() == null || uid.getText().length() <= 0) {

			Toast.makeText(this, "请输入用户名", 3).show();

			return false;
		}

		if (upwd.getText() == null || upwd.getText().length() <= 0) {
			Toast.makeText(this, "请输入密码", 3).show();

			return false;
		}

		return true;
	}

	private void LoginRequse() {
		try {
			JSONObject jb = new JSONObject();
			jb.put("userCode", uid.getText().toString());
			jb.put("password", upwd.getText().toString());
			String url = Config.domain + Config.LOGIN_URL + java.net.URLEncoder.encode(jb.toString(), "utf-8");

			if (this.task != null) {
				this.task.detachActivity();
				this.task.cancel(true);
				this.task = null;
			}
			this.task = new LoginAsyncTask();
			this.task.attachActivity(this);
			this.startLogin.setVisibility(View.VISIBLE);
			this.btnLogin.setEnabled(false);

			AsyncTaskFactory factory = new AsyncTaskFactory();
			factory.build().execute(this.task, url);
		} catch (IOException e) {
			Toast.makeText(this, "请检查服务器连接设置" + e.getMessage(), 3).show();
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onDetachedFromWindow() {
		if (this.task != null) {
			this.task.detachActivity();
		}

		super.onDetachedFromWindow();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private class LoginAsyncTask extends AsyncTask<String, Void, String> {
		private Activity activity;

		public void attachActivity(Activity activity) {
			this.activity = activity;
		}

		public void detachActivity() {
			this.activity = null;
		}

		@Override
		protected String doInBackground(String... arg0) {
			String url = arg0[0];
			Log.d("LoginActivity", "doInBackground  url==" + url);
			String code = Util.getResponseBody(url);

			try {
				NSArray menuListArray = (NSArray) PropertyListParser.parse(this.activity.getAssets().open("menuData.plist"));
				GlobalData.getInstance().setMenuListArray(menuListArray);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

			Log.d("LoginActivity", "doInBackground  code==" + code);
			return code;
		}

		@Override
		protected void onPostExecute(String code) {
			super.onPostExecute(code);

			startLogin.setVisibility(View.GONE);
			btnLogin.setEnabled(true);

			if (this.activity != null) {
				if (code.length() < 1) {
					Toast.makeText(this.activity, "请检查服务器连接设置:" + code, 3).show();
					return;
				}

				Double flag = (Double) new Gson().fromJson(code, Map.class).get("flag");
				Config.suppliercode = (String) new Gson().fromJson(code, Map.class).get("suppliercode");
				if (flag == 1) {
					Editor editor = sharedPreferences.edit();
					if (checkBox.isChecked()) {
						editor.putString("uid", uid.getText().toString());
						editor.putString("pass", upwd.getText().toString());
						editor.commit();
					} else {
						editor.clear();
						editor.commit();
					}
					editor = null;

					Intent intent = new Intent(LoginActivity.this, IndexActivity.class);
					startActivity(intent);
					finish();
				} else if (flag == 3) {
					Toast.makeText(this.activity, "用户或密码错误", 3).show();
				} else {
					Toast.makeText(this.activity, "登陆失败", 3).show();
				}
			}
		}

	}
}
